import axios from 'axios'
import { VueAxios } from './axios'
import router from '@/router'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // // 从 localstorage 获取 token
    // const token = storage.get(ACCESS_TOKEN)
    if(data.status==500 && data.message=='Token失效，请重新登录'){
      localStorage.removeItem('jyToken')
      localStorage.removeItem('userInfo')
      router.replace({name:'Login'})
    }
    if (error.response.status === 403) {

    }
    if (error.response.status === 401) {
      localStorage.removeItem('jyToken')
      router.replace({name:'Login'})
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = localStorage.getItem('jyToken')
  // // 如果 token 存在
  // // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['X-Access-Token'] = token
  }
  if(!config.headers['Content-Type']){
    config.headers['Content-Type'] ='application/x-www-form-urlencoded'
  } 
  // console.log(config,'config=======')
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  // console.log(response,'response')
  if (response.status === 401||response.data.code === 401) {
    localStorage.removeItem('jyToken')
    localStorage.removeItem('userInfo')
    router.replace({name:'Login'})
    return false
  }
  // if (response.data.status === 500&&response.data.message=='Token失效，请重新登录') {
  //   localStorage.removeItem('jyToken')
  //   localStorage.removeItem('userInfo')
  //   router.replace({name:'Login'})
  //   return false
  // }
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
